//
//  CommentVC.m
//  Echo
//
//  Created by Cospring on 14/12/17.
//  Copyright (c) 2014年 sina. All rights reserved.
//

#import "CommentVC.h"
#import "CommentCell.h"
#import "UIConfig.h"
#import "Comment.h"
#import "SVProgressHUD.h"

@interface CommentVC ()

@end

@implementation CommentVC {
    UIView *emptyView;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self registerForKeyboardNotifications];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self deregisterForKeyboardNotifications];
}

- (void)dealloc
{
    [self deregisterForKeyboardNotifications];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.commentTableView.delegate = self;
    self.commentTableView.dataSource = self;
    self.commentTableView.separatorColor = [UIColor clearColor];
    self.commentTableView.showsHorizontalScrollIndicator = NO;
    self.commentTableView.showsVerticalScrollIndicator = NO;
    
    //UITableViewCellSeparatorStyle
    self.commentTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    
    [self.commentTableView registerNib:[UINib nibWithNibName:@"CommentCell" bundle:nil] forCellReuseIdentifier:@"CommentCell"];
    
//    self.commentDataList = [[NSMutableArray alloc] init];
    
//    for (int i = 0; i < 30; i++) {
//        [self.commentDataList addObject:@{@"name":@"oo春寒料峭oo", @"text":@"做英语阅读的感觉：我们知道賢鏛是在生活中很重要的。比如在鼙蠻和贎鬍里，有彃燊在罅鷄那里蘩墝，之前他们鏈鴊恆闳嘑傡彚槩滼鞷蕻賤鬡艐倏雫寬褲灣曠隗谡堅鑷蠵。1，鞷 在文中的意思？ 2，这篇文章的最佳标题？3，作者没有告诉我们什么？", @"url":@"http://tp4.sinaimg.cn/1888255567/180/1292411105/1", @"date":@"2014-08-08"}];
//    }
    
    self.commentTextField.delegate = self;
    
//    self.commentTextField.inputAccessoryView = self.commentBoxView;
//    self.commentBoxView.layer.zPosition = 2.0;
    
    [self setUpForDismissKeyboard];
    
    
}

- (void)setCommentList:(NSArray *)commentList
{
    _commentList = commentList;
    NSLog(@"commentList = %@", commentList);
    if (commentList == nil || [commentList count] == 0) {
        if (emptyView == nil) {
            NSArray *subviewArray = [[NSBundle mainBundle] loadNibNamed:@"commentPlaceholder" owner:nil options:nil];
            emptyView = [subviewArray objectAtIndex:0];
            emptyView.frame = self.commentTableView.frame;
            [emptyView setNeedsUpdateConstraints];
        }
        
        [self.view addSubview:emptyView];
        [self.view bringSubviewToFront:self.commentTableView];
        self.commentTableView.layer.opacity = 0.1;
    } else {
        if (emptyView) {
            [emptyView removeFromSuperview];
        }
        self.commentTableView.layer.opacity = 1;
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    //    NSLog(@"%f",scrollView.contentOffset.y);
    if (scrollView.contentOffset.y < -100) {
        [self.commentVCDelegate scrollToTop];
    }
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.commentList count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CommentCell *cell = [self.commentTableView dequeueReusableCellWithIdentifier:@"CommentCell" forIndexPath:indexPath];
    cell.comment = self.commentList[indexPath.row];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return [CommentCell heightForCommentCell:self.commentList[indexPath.row]];
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */


- (void)tapAnywhereToDismissKeyboard:(UITapGestureRecognizer *)sender
{
    [self.view endEditing:YES];
}

- (void)setUpForDismissKeyboard
{
    UITapGestureRecognizer *singleTapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAnywhereToDismissKeyboard:)];
    
    NSOperationQueue *mainQueue = [NSOperationQueue mainQueue];
    
    [[NSNotificationCenter defaultCenter] addObserverForName:UIKeyboardWillShowNotification object:nil queue:mainQueue usingBlock:^(NSNotification *note) {
        [self.commentTableView addGestureRecognizer:singleTapGR];
    }];
    
    [[NSNotificationCenter defaultCenter] addObserverForName:UIKeyboardWillHideNotification object:nil queue:mainQueue usingBlock:^(NSNotification *note) {
        [self.commentTableView removeGestureRecognizer:singleTapGR];
    }];
}

- (void)submitComment
{
    NSLog(@"submitComment");
    [Comment addCommentByCurrentUserToTweet:_mid WithText:_commentTextField.text WithBlock:^(Comment *newComment, NSError *error) {
        
        [SVProgressHUD showSuccessWithStatus:@"评论成功!"];
        _commentTextField.text = @"";
        [_commentTextField resignFirstResponder];
        
        NSMutableArray *array = [[NSMutableArray alloc] initWithArray:self.commentList];
        [array insertObject:newComment atIndex:0];
        self.commentList = array;
        [self.commentTableView reloadData];
        if (emptyView) {
            emptyView.hidden = true;
        }
    }];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    NSLog(@"textFieldShouldReturn");
    [self submitComment];
    return YES;
}


- (void)registerForKeyboardNotifications
{
    NSLog(@"registerForKeyboardNotifications");
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShown:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillBeHidden:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)deregisterForKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

bool animationLock = false;

- (void)keyboardWillShown:(NSNotification *)notification
{
    NSLog(@"keyboardWillShown");
//    if (animationLock) {
//        return;
//    }
    [self.view bringSubviewToFront:self.commentBoxView];
    NSDictionary *info = [notification userInfo];
    CGRect keyboardFrame = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat offsetY = SCREEN_HEIGHT - keyboardFrame.size.height - COMMENTBOX_HEIGHT - 80;
    NSLog(@"keyboardFrame.size.height = %f", keyboardFrame.size.height);
    animationLock = true;
    
    [UIView animateWithDuration:0.8 animations:^{
        CGRect rect = self.commentBoxView.frame;
        rect.origin.y = offsetY;
        self.commentBoxView.frame = rect;
    } completion:^(BOOL finished) {
        animationLock = false;
    }];
}

- (void)keyboardWillBeHidden:(NSNotification *)notification
{
    NSLog(@"keyboardWillBeHidden");
    NSDictionary *info = [notification userInfo];
    CGRect keyboardFrame = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat offsetY = self.commentBoxView.frame.origin.y + keyboardFrame.size.height;
    
    [UIView animateWithDuration:0.8 animations:^{
        CGRect rect = self.commentBoxView.frame;
        rect.origin.y = offsetY;
        self.commentBoxView.frame = rect;
    }];
}

- (IBAction)postComment:(id)sender {
    [self submitComment];
}
@end








